package com.example.controller;

import com.example.service.HelloRemote;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/hello")
public class HelloController {
    //负载均衡客户端接口
    @Autowired
    private LoadBalancerClient client;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private HelloRemote helloRemote;

    @RequestMapping("/1")
    public String hello(@RequestParam String name) {
        name += "!";
        //根据spring.application.name从注册中心找到该服务
        ServiceInstance instance = client.choose("eureka-producer");
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/hello/?name=" + name;
        return restTemplate.getForObject(url, String.class);
    }

    /**
     * ribbon 负载均衡方式
     * @param name
     * @return
     */
    @RequestMapping("/2")
    public String hello2(@RequestParam String name) {
        name += "!";
        //根据spring.application.name从注册中心找到该服务
        String url = "http://eureka-producer/hello/?name=" + name;
        return restTemplate.getForObject(url, String.class);
    }

    /**
     * feign 方式调用
     * @param name
     * @return
     */
    @RequestMapping("/3")
    //添加熔断方法
//    @HystrixCommand(fallbackMethod = "fall")
    public String hello3(@RequestParam String name) {
        return helloRemote.hello(name + "!");
    }

    public String fall(String name, Throwable e) {
        return "失败";
    }
}
